//app.js
import { getCode, sendCode, getUserInfo } from './service/app.js';
App({
  onLaunch: function (options) {
    console.log(options)
    // 登录
    if (!wx.getStorageSync('token')) {
      this._getCode()
    }
  },
  _getCode() { // 获取code
    let _this = this;
    getCode((res) => {
      res.code ? this._sendCode(res.code) : console.log('获取用户登录态失败！' + res.errMsg);
      if (_this.userInfoReadyCallback) {
        _this.userInfoReadyCallback(res)
      }
    }, (res) => {
      console.log('login fail: ' + res.errMsg);
    })
  },
  _sendCode(code) { // 发送code获取token
    let _this = this;
    sendCode(code).then(res => {
      if (res.data) {
        let data = res.data
        data.get_session_timestamp = (new Date()).getTime();
        wx.setStorageSync('token', res.data.token)
        // wx.switchTab({
        //   url: '/pages/index/index'
        // })
      }
      if (_this.userInfoReadyCallback) {
        _this.userInfoReadyCallback(res)
      }
      return true;
    }).catch(err => {
      console.log('_sendCode fail');
    });
  },
  globalData: {
    userInfo: null
  }
})